﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LumiSoft.Net.POP3.Client;
using LumiSoft.Net;
using Baosight.Ccs.Mail.Properties;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Baosight.Ccs.Mail
{
    /// <summary>
    /// 接受邮件管理器
    /// <remarks>
    /// 简单考虑，先只考虑从1个邮箱接受邮件的情况。
    /// </remarks>
    /// </summary>
    public class ReceiveMailManager
    {
        private string pop3Server = Settings.Default.Pop3Server;

        private string user = Settings.Default.Pop3User;

        private string credential = Settings.Default.Pop3Credential;

        //private string port;

        public void ReceiveMails()
        {
            using (POP3_Client pop3Client = new POP3_Client())
            {
                pop3Client.Connect(pop3Server, WellKnownPorts.POP3);

                pop3Client.Authenticate(user, credential, false);

                var mails = from POP3_ClientMessage message in pop3Client.Messages
                            select message.GetMailFromPop3Message();
                foreach (Mail mail in mails)
                {
                    try
                    {
                        MailManager.Instance.PersistUnhandledMail(mail);
                        if (mail.OriginalMessage != null)
                        {
                            //remove from mail server
                            mail.OriginalMessage.MarkForDeletion();
                        }

                    }
                    catch (Exception ex)
                    {
                        ExceptionPolicy.HandleException(ex, MailConstants.PersistMailFailExceptionPolicy);
                    }
                }
            }
            
        }
    }
}
